package com.beta.restapi.controller.upload;

import com.beta.entity.ProductItems;
import com.beta.service.IProductItemsService;
import com.beta.support.ResourceImagePathBuilder;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Created by vector on 2017/1/5.
 */
@Component
public class ProductItemSliderImageHandler extends AbstractImageHandler implements IImageHandler {

    @Autowired
    private IProductItemsService productItemsService;

    @Override
    public boolean supportType(String pictureType) {
        return "product_item_slider".equals(pictureType);
    }

    @Override
    public String buildRelativePathForSave(HttpServletRequest request, Integer userId, String fileName) {
        return ResourceImagePathBuilder.productSlideImagePath(getProductItemId(request), getSliderIndex(request), fileName);
    }

    @Override
    protected String buildImageRelativePathForDelete(HttpServletRequest request, Integer userId) {
        Integer productItemId = getProductItemId(request);
        ProductItems productItems = productItemsService.selectById(productItemId);
        if (Objects.isNull(productItems)) {
            return null;
        }

        try {
            Integer sliderIndex = getSliderIndex(request);
            String sliderImgPath = BeanUtils.getProperty(productItems, "slide_img_path" + sliderIndex);
            return ResourceImagePathBuilder.productSlideImagePath(productItemId, sliderIndex, sliderImgPath);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void afterImageSave(HttpServletRequest request, Integer userId, String fileName) {
        productItemsService.updateSliderImage(getProductItemId(request), getSliderIndex(request), fileName);
    }

    @Override
    protected void afterImageDelete(HttpServletRequest request, Integer userId) {
        super.afterImageDelete(request, userId);

    }

    private Integer getProductItemId(HttpServletRequest request) {
        return Integer.parseInt(request.getParameter("product_item_id"));
    }

    private Integer getSliderIndex(HttpServletRequest request) {
        return Integer.parseInt(request.getParameter("slider_image_index"));
    }

}
